<?php
/**
 * Created by JetBrains PhpStorm.
 * User: User
 * Date: 24.05.12
 * Time: 16:04
 * To change this template use File | Settings | File Templates.
 */


class SJB_Admin_Miscellaneous_UpdateToNewVersion extends SJB_Function
{
	public function isAccessible()
	{
		return true;
	}

	public function execute()
	{
		$tp     = SJB_System::getTemplateProcessor();
		$errors = array();

		$updatesDir = SJB_System::getSystemSettings('SJB_UPDATES_DIR');

		$updateToVer = SJB_Request::getVar('to_version');
		if (!empty($updateToVer)) {
			// remove all path elements
			$updateToVer = basename($updateToVer);
			$startPath = $updatesDir . DIRECTORY_SEPARATOR . $updateToVer . DIRECTORY_SEPARATOR . "updater.php";

			if (file_exists($startPath)) {
				include_once $startPath;
			} else {
				echo '<p class="error">Update package files are missing</p>';
			}
			$tp->display('updater_starts.tpl');
		} else {
			$formSubmitted = SJB_Request::getVar('update_to_version');
			if (!empty($formSubmitted)) {
				// OK. we need to create Zend_Rest_Client, check user and get available updates if allowed
				$client = new Zend_Rest_Client(SJB_System::getSystemSettings('SJB_UPDATE_SERVER_URL'));

				$result = $client->getUpdateLink(
					SJB_Request::getVar('auth_username'),
					SJB_Request::getVar('auth_password'),
					SJB_System::getSystemSettings('version'))->get();

				if ($result->isSuccess()) {
					if (isset($result->error))
						$errors[] = (string) $result->error;
					if (isset($result->update)) {
						$updateLink = (string) $result->update;
						// is update file accessible?
						$fp = fopen($updateLink, 'rb');
						if ($fp !== false) {
							// close resource. copy() function will be used to download file
							fclose($fp);
							$downloadedFileName = basename($updateLink);
							$unzipDirname       = basename($updateLink, '.zip');
							$downloadedFilePath = $updatesDir . DIRECTORY_SEPARATOR . $downloadedFileName;
							// download update file to cache/updates folder
							$result = copy($updateLink, $downloadedFilePath);

							if ($result) {
								if (extension_loaded('zip')) {
									$zip = new ZipArchive;
									$res = $zip->open($downloadedFilePath);
									if ($res === true) {
										$zip->extractTo($updatesDir . DIRECTORY_SEPARATOR . $unzipDirname . DIRECTORY_SEPARATOR);
										$zip->close();
										SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('ADMIN_SITE_URL') . '/update-to-new-version/?to_version=' . urlencode($unzipDirname));
									}
									else {
										$errors[] = 'Failed to extract upgrade package files';
									}
								}
							}
							else {
								$errors[] = 'Failed to download upgrade package';
							}
						}
						else {
							$errors[] = 'Failed to download upgrade package';
						}
					}
				}
			}

			$tp->assign('errors', $errors);
			$tp->display('update_to_new_version.tpl');
		}
	}

}